package com.xgj.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

//拦截器使用：只拦截controller接口
public class MyInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(MyInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 记录请求开始时间
        long startTime = System.currentTimeMillis();
        request.setAttribute("startTime", startTime);

        // 记录请求信息
        logger.info("=== 拦截器前置处理 ===");
        logger.info("请求URI: {}", request.getRequestURI());
        logger.info("请求方法: {}", request.getMethod());

        // 打印请求头（调试用）
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            logger.debug("请求头 {}: {}", headerName, request.getHeader(headerName));
        }

        // 示例：简单的权限验证
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            logger.warn("未授权的访问 - 缺少有效的Authorization头");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"error\":\"Unauthorized\"}");
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        logger.info("=== 拦截器后置处理 ===");
        logger.info("响应状态: {}", response.getStatus());

        // 可以修改响应数据
        if (modelAndView != null) {
            logger.info("视图名称: {}", modelAndView.getViewName());
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
        logger.info("=== 拦截器完成处理 ===");
        long startTime = (Long) request.getAttribute("startTime");
        long duration = System.currentTimeMillis() - startTime;
        logger.info("请求处理耗时: {}ms", duration);

        if (ex != null) {
            logger.error("请求处理异常: {}", ex.getMessage(), ex);
        }
    }
}
